package com.cy.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
public class AjaxController {


    private List<Map<String,Object>> dblist = new ArrayList<>();

    public AjaxController(){
        Map<String,Object> map = new HashMap<>();
        map.put("id", 100);
        map.put("D", "道");
        map.put("C", "诚");
        map.put("M", "某");
        dblist.add(map);
    }

    @RequestMapping("/doAjaxGet")
    public List<Map<String,Object>> doAjaxGet(){
        return dblist;
    }

    @RequestMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        map.put("createTime", new Date());
        dblist.add(map);
        return "save ok";
    }

    @RequestMapping("/doAjaxDelete")
    public String doAjaxDelete(String id) {

        Iterator it = dblist.iterator();
        while (it.hasNext()){
            Map<String,Object> map = (Map<String, Object>)it.next();
            if (map.get("id").equals(id));{
                it.remove();
            }
        }

//        Iterator<Map<String, Object>> it = dblist.iterator();
//        while (it.hasNext()) {
//            Map<String, Object> map = it.next();
//            if (map.get("id").equals(id)) {
////                map.remove(map);
//                it.remove();
//            }
//        }
        return "delete ok";
    }
    @PutMapping("/doAjaxUpdate")
    public String doAjaxUpdate(@RequestParam Map<String,Object> updateMap){
        Iterator it = dblist.iterator();
        while (it.hasNext()){
            Map<String,Object> map = (Map<String,Object>)it.next();
            if (map.get("id").equals(updateMap.get("id"))){
                map.put("name", updateMap.get("name"));
                map.put("remark", updateMap.get("remark"));
            }
        }
        return "update ok";
    }


    @CrossOrigin//@CrossOrigin注解描述
    @RequestMapping("/doAjaxStart01")
    public String doAjaxAGet01() throws InterruptedException {

        Thread.sleep(2000);
        return "Response Request Of Ajax Get Request 01";
    }
}
